import React, { useContext, useEffect, useState } from 'react';
import {
    Alert,
    DeviceEventEmitter,
    ImageBackground,
    RefreshControl, ScrollView,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import { Icon, Image, ListItem, Text } from 'react-native-elements';
import LocaleContext from '../libs/locale';
import WalletContext from '../libs/wallet';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {delRedRepub, getRedRepubDB} from "./RedEnvelopeRepubDB";
import {constansts} from "../libs/constansts";
import sETHlogo from "../assets/1.png";
import susdtlogo from "../assets/susdt.png";
import otherTokenLogo from "../assets/hotTokenLogo.png";
import SATlogo from '../assets/logo.png';
import {SendRedEnvelope} from "../libs/nodes";
import Clipboard from "@react-native-community/clipboard";
import Toast from "react-native-simple-toast";
import {dropGestureHandler} from "react-native-gesture-handler/lib/typescript/web/NodeManager";



const RedEnvelopeRepub = ({navigation,route}:any) =>{
    const locale = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [refresh, setRefresh] = useState(true);
    const [RedEnvelopeRepubList,setRedEnvelopeRepubList] = useState([]);

    useEffect(()=>{
        const work = async () => {
            if(!refresh)
            {
                return ;
            }
            setRefresh(false);
            let RePubDate = await getRedRepubDB();
            setRedEnvelopeRepubList(RePubDate);
            console.log(JSON.stringify(RePubDate))
        }
        work();
    },[refresh])

    const getTokenUrl = (tokenAddress:string) => {

        for( let i = 0 ; i < constansts.HotTokens.length ; i++)
        {
            if(tokenAddress === constansts.HotTokens[i].address)
            {
                return constansts.HotTokens[i].url;
            }
        }
        return "";

    }
    const onCopy = (date:string) => {
        Clipboard.setString(date);
        Toast.show(locale?._('copied') as string);
    };

    return (
        <View>
            <View style={{flexDirection:"row",justifyContent:"center"}}>
                {/*<Text style={{marginLeft:"2%",alignSelf:"center",fontWeight:"bold"}}>取消</Text>*/}
            </View>
            {
                <Text style={{marginTop:15,marginLeft:20,fontWeight:"bold",fontSize:18}}>{locale?._("RedRepub.SmallTitle")}</Text>
            }
            <ScrollView refreshControl={
                <RefreshControl refreshing={false} onRefresh={() => setRefresh(true)} collapsable={true} />} >
                <View >
                    {
                        RedEnvelopeRepubList.length
                            ?
                            RedEnvelopeRepubList.map((tx: any,index:any) => (
                                <ListItem bottomDivider
                                          onPress={ async () => {
                                              let res:any;
                                              if(tx.tokenAddress=="")
                                              {
                                                  res = await SendRedEnvelope(wallet.address, tx.hash, tx.num, tx.total,tx.bless,'','');
                                              }
                                              else
                                              {
                                                  res = await SendRedEnvelope(wallet.address, tx.hash, tx.num, tx.total,tx.bless,tx.tokenName,tx.tokenAddress);
                                              }
                                              if(res.ret==-1)
                                              {
                                                  Alert.alert("",locale?._("RedEnvelopeInfo.AlertSendFalse"))
                                              }
                                              else
                                              {
                                                  Alert.alert("",locale?._("RedEnvelopeIndex.RedEnvelopeTip1")+"：("+res.dict.pkgid+")"+"   "+tx.tokenName+"\n"+locale?._("RedEnvelopeIndex.RedEnvelopeTip2")+":  https://smartxdown.lanzoul.com/b036y4ftc   password:smartx"+"\n"+locale?._("RedEnvelopeIndex.RedEnvelopeTip3")+"  https://red.smartx.one/#/?pkgid="+res.dict.pkgid,[{
                                                      text: locale?._('ok'),
                                                      onPress: async () => {
                                                          onCopy(locale?._("RedEnvelopeIndex.RedEnvelopeTip1")+"：("+res.dict.pkgid+")"+"   "+tx.tokenName+"\n"+locale?._("RedEnvelopeIndex.RedEnvelopeTip2")+":  https://smartxdown.lanzoul.com/b036y4ftc   password:smartx"+"\n"+locale?._("RedEnvelopeIndex.RedEnvelopeTip3")+" https://red.smartx.one/#/?pkgid="+res.dict.pkgid);
                                                          let delRes = await delRedRepub(tx);
                                                          console.log(delRes);
                                                          setRefresh(true);
                                                      }}])
                                              }
                                }}  key={index}>
                                    {
                                        tx.tokenAddress==constansts.contractAddressImage.sETH?
                                            <ImageBackground source={sETHlogo} style={{ width: 38, height: 38 }} />
                                            :
                                            (
                                                tx.tokenAddress==constansts.contractAddressImage.sUSDT?
                                                    <ImageBackground source={susdtlogo} style={{ width: 38, height: 38 }} />
                                                    :
                                                    (
                                                        tx.tokenAddress==""?
                                                            <ImageBackground source={SATlogo} style={{ width: 38, height: 38 }} />
                                                            :
                                                            (
                                                                getTokenUrl(tx.tokenAddress)==""?
                                                                <ImageBackground source={otherTokenLogo} style={{ width: 38, height: 38 }} />
                                                                :
                                                                <ImageBackground source={{uri:getTokenUrl(tx.tokenAddress)}} style={{ width: 38, height: 38 }} />
                                                            )
                                                    )
                                            )
                                    }
                                    <ListItem.Content>
                                        <ListItem.Title style={{fontSize:13}}>{tx.total} {tx.tokenName==""?"SAT":`(${tx.tokenName})`}</ListItem.Title>
                                        <ListItem.Subtitle style={{fontSize:11}}>{tx.num}</ListItem.Subtitle>
                                    </ListItem.Content>
                                    {
                                        <Icon type='feather' name='send' color='#7259E0FF' size={26}  />
                                    }
                                </ListItem>
                            ))
                            :
                            <View style={{ flex: 1, justifyContent: 'center' }}>
                                <Text style={{
                                    marginTop: '100%',
                                    fontSize: 20,
                                    textAlign: 'center',
                                    color: 'grey'
                                }}>{locale?._('noContent')}</Text>
                            </View>
                    }

                </View>
            </ScrollView>
        </View>
    );

};
export default RedEnvelopeRepub;
